package com.qyhl.webtv.module_microvideo.shortvideo.search;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoBean;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoSearchBean;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoThemeBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.GridDividerItemDecoration;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索页面
 */
@Route(path = ARouterPathConstant.SHORT_VIDEO_SEARCH)
public class ShortVideoSearchActivity extends BaseActivity implements ShortVideoSearchContract.ShortVideoSearchView {
    @BindView(R2.id.commit_canel_btn)
    TextView commitCanelBtn;
    @BindView(R2.id.input_edt)
    EditText inputEdt;
    @BindView(R2.id.flow_layout)
    TagFlowLayout flowLayout;
    @BindView(R2.id.hot_layout)
    LinearLayout hotLayout;
    @BindView(R2.id.relative_flowlayout)
    TagFlowLayout relativeFlowlayout;
    @BindView(R2.id.relative_theme_layout)
    LinearLayout relativeThemeLayout;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.relative_works)
    LinearLayout relativeWorks;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    private ShortVideoSearchPresenter mPresenter;

    @Autowired(name = "type")
    String type;

    @Autowired(name = "id")
    String activityId;

    private List<ShortVideoThemeBean> hotTagList = new ArrayList<>();

    private List<ShortVideoThemeBean> relativeTagList = new ArrayList<>();

    private CommonAdapter commonAdapter;

    private List<ShortVideoBean> mDataList = new ArrayList<>();

    private String keyWords = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.micro_activity_short_video_search;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new ShortVideoSearchPresenter(this);
        activityId = getIntent().getStringExtra("id");
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getHotTheme(activityId);
    }

    private void initView() {
        loadMask.setStatus(LoadingLayout.Success);
        flowLayout.setMaxSelectCount(0);
        relativeFlowlayout.setMaxSelectCount(0);

        hotLayout.setVisibility(View.VISIBLE);
        relativeThemeLayout.setVisibility(View.GONE);
        relativeWorks.setVisibility(View.GONE);

        recycleView.setLayoutManager(new GridLayoutManager(this, 2));
        recycleView.addItemDecoration(new GridDividerItemDecoration(4, getResources().getColor(R.color.micro_short_video_bg)));

        recycleView.setAdapter(commonAdapter = new CommonAdapter<ShortVideoBean>(this, R.layout.micro_item_short_video_home, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShortVideoBean bean, int position) {
                TextView summary = holder.getView(R.id.summary);
                summary.setText(markKeyWords(bean.getTitle(), false));
                holder.setText(R.id.user_nickname, bean.getUserNickName());
                holder.setText(R.id.hot_value, bean.getScore() + "");

                ImageView cover = holder.getView(R.id.cover);
                Glide.with(ShortVideoSearchActivity.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);

                RoundedImageView headIcon = holder.getView(R.id.user_avatar);
                Glide.with(ShortVideoSearchActivity.this)
                        .load(bean.getUserLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(headIcon);

            }
        });
    }

    private void setListeners() {
        flowLayout.setOnTagClickListener((view, position, parent) -> {
            if (type.equals("tag")) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", hotTagList.get(position));
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("id", hotTagList.get(position).getId() + "");
                bundle.putString("actId", activityId);
                RouterManager.router(ARouterPathConstant.SHORT_VIDEO_THEME_DETAIL,bundle);
            }
            return false;
        });

        relativeFlowlayout.setOnTagClickListener((view, position, parent) -> {
            if (type.equals("tag")) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", relativeTagList.get(position));
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            } else {

                Bundle bundle = new Bundle();
                bundle.putString("id", hotTagList.get(position).getId() + "");
                bundle.putString("actId", activityId);
                RouterManager.router(ARouterPathConstant.SHORT_VIDEO_THEME_DETAIL,bundle);

            }
            return false;
        });

        inputEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyWords = s.toString();
                if (StringUtils.isNotEmpty(s.toString()) && s.toString().trim().length() > 0) {
                    commitCanelBtn.setText("确定");
                } else {
                    commitCanelBtn.setText("取消");
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", (Serializable) mDataList);
                bundle.putString("actId", activityId);
                bundle.putInt("position", position);
                bundle.putInt("page", 0);
                bundle.putInt("type", 0);

                RouterManager.router(ARouterPathConstant.SHORT_VIDEO_PLAY,bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void setHotTheme(List<ShortVideoThemeBean> beanList) {
        hotLayout.setVisibility(View.VISIBLE);
        hotTagList.clear();
        hotTagList.addAll(beanList);
        flowLayout.setAdapter(new TagAdapter<ShortVideoThemeBean>(hotTagList) {
            @SuppressLint("SetTextI18n")
            @Override
            public View getView(FlowLayout parent, int position, ShortVideoThemeBean bean) {
                TextView tv = (TextView) LayoutInflater.from(ShortVideoSearchActivity.this).inflate(R.layout.micro_item_short_video_hot_tag,
                        flowLayout, false);
                tv.setText("#" + bean.getName() + "#");
                return tv;
            }
        });

    }

    @Override
    public void setHotError(String msg) {
        hotLayout.setVisibility(View.GONE);
        Log.d("sv_error:", msg);
    }

    @Override
    public void setSearch(ShortVideoSearchBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        if (type.equals("tag")) {
            hotLayout.setVisibility(View.GONE);
            relativeThemeLayout.setVisibility(View.VISIBLE);
            relativeWorks.setVisibility(View.GONE);
            setTag(bean);
        } else if (type.equals("all")) {
            hotLayout.setVisibility(View.GONE);
            if (bean.getTags() != null && bean.getTags().size() > 0) {
                relativeThemeLayout.setVisibility(View.VISIBLE);
                setTag(bean);
            } else {
                relativeThemeLayout.setVisibility(View.GONE);
            }

            if (bean.getWorks() != null && bean.getWorks().size() > 0) {
                relativeWorks.setVisibility(View.VISIBLE);
                setWorks(bean);
            } else {
                relativeWorks.setVisibility(View.GONE);
            }
        }
    }

    private void setWorks(ShortVideoSearchBean bean) {
        mDataList.clear();
        mDataList.addAll(bean.getWorks());
        commonAdapter.notifyDataSetChanged();
    }

    private void setTag(ShortVideoSearchBean bean) {
        relativeTagList.clear();
        relativeTagList.addAll(bean.getTags());
        relativeFlowlayout.setAdapter(new TagAdapter<ShortVideoThemeBean>(relativeTagList) {
            @SuppressLint("SetTextI18n")
            @Override
            public View getView(FlowLayout parent, int position, ShortVideoThemeBean bean) {
                TextView tv = (TextView) LayoutInflater.from(ShortVideoSearchActivity.this).inflate(R.layout.micro_item_short_video_hot_tag,
                        relativeFlowlayout, false);
                tv.setText(markKeyWords(bean.getName(), true));
                return tv;
            }
        });
    }

    private SpannableStringBuilder markKeyWords(String str, boolean isTag) {
        if (isTag) {
            str = "#" + str + "#";
        }
        String start = str.substring(0, str.indexOf(keyWords));
        String end = str.substring(str.indexOf(keyWords) + keyWords.length(), str.length());
        SpanUtils spanUtils = new SpanUtils(this);
        if (StringUtils.isNotEmpty(start)) {
            if (isTag) {
                spanUtils.append(start).setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_search_tag_off));
            } else {
                spanUtils.append(start).setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_search_work_off));
            }

        }
        spanUtils.append(keyWords).setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_search_on));
        if (StringUtils.isNotEmpty(end)) {
            if (isTag) {
                spanUtils.append(end).setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_search_tag_off));
            } else {
                spanUtils.append(end).setSpans(new TextAppearanceSpan(this, R.style.micro_short_video_search_work_off));
            }
        }
        return spanUtils.create();
    }

    @Override
    public void setSearchError(String msg) {
        hotLayout.setVisibility(View.GONE);
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setEmptyImage(R.drawable.empty_content);
    }

    @OnClick({R2.id.commit_canel_btn, R2.id.clear})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.commit_canel_btn) {
            if (commitCanelBtn.getText().toString().equals("取消")) {
                finish();
            } else {
                mPresenter.goSearch(activityId, keyWords, type);
            }
        } else if (i == R.id.clear) {
            inputEdt.setText("");
        }
    }
}
